package com.zky.gulimall.search.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zky.common.to.es.SkuEsModel;
import com.zky.common.utils.R;
import com.zky.gulimall.search.Service.MallSearchServie;
import com.zky.gulimall.search.config.ElasticSearchConfig;
import com.zky.gulimall.search.constant.EsConstant;
import com.zky.gulimall.search.feign.ProductFeignService;
import com.zky.gulimall.search.vo.AttrResponseVo;
import com.zky.gulimall.search.vo.BrandResponseVo;
import com.zky.gulimall.search.vo.SearchParam;
import com.zky.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 检索service
 * @Author 张开源
 * @Date 2022/11/9 9:23
 * @Version 1.0
 **/
@Service
@Slf4j
public class MallSearchServieImpl implements MallSearchServie {
    @Resource
    private RestHighLevelClient highLevelClient;
    @Resource
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        //动态构建检索请求
        SearchRequest request = buildSearchRequest(param);

        SearchResult result = null;

        try {
            //检索数据
            SearchResponse response = highLevelClient.search(request, ElasticSearchConfig.COMMOM_OPTIONS);

            //组装响应结果
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param response
     * @param param
     * @return SearchResult
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();

        //查询商品
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        SearchHit[] hitsHits = hits.getHits();
        if (hitsHits != null & hitsHits.length > 0) {
            for (SearchHit hitsHit : hitsHits) {
                String source = hitsHit.getSourceAsString();
                SkuEsModel model = JSON.parseObject(source, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    Map<String, HighlightField> fields = hitsHit.getHighlightFields();
                    if (!CollectionUtils.isEmpty(fields)) {
                        String skuTitle = fields.get("skuTitle").getFragments()[0].string();
                        model.setSkuTitle(skuTitle);
                    }
                }
                skuEsModels.add(model);
            }
        }
        result.setProducts(skuEsModels);

        //商品属性聚合结果
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        if (!CollectionUtils.isEmpty(buckets)) {
            for (Terms.Bucket bucket : buckets) {
                SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
                //获取三级分类id
                String key = bucket.getKeyAsString();
                catalogVo.setCatalogId(Long.parseLong(key));

                //获取子聚合三级分类名称
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                List<? extends Terms.Bucket> list = catalog_name_agg.getBuckets();
                if (!CollectionUtils.isEmpty(list)) {
                    String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                    catalogVo.setCatalogName(catalog_name);
                }
                catalogVos.add(catalogVo);
            }
        }
        result.setCatalogs(catalogVos);


        //当前商品涉及到的所有品牌
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket aggBucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //获取品牌id
            brandVo.setBrandId(aggBucket.getKeyAsNumber().longValue());
            //获取品牌名
            //获取名称子聚合
            ParsedStringTerms brand_name_agg = aggBucket.getAggregations().get("brand_name_agg");
            List<? extends Terms.Bucket> brand_name_aggBuckets = brand_name_agg.getBuckets();
            if (!CollectionUtils.isEmpty(brand_name_aggBuckets)) {
                String brand_name = brand_name_aggBuckets.get(0).getKeyAsString();
                brandVo.setBrandName(brand_name);
            }
            //获取品牌图片
            ParsedStringTerms brand_img_agg = aggBucket.getAggregations().get("brand_img_agg");
            List<? extends Terms.Bucket> brandImgAggBuckets = brand_img_agg.getBuckets();
            if (!CollectionUtils.isEmpty(brandImgAggBuckets)) {
                String brand_img = brandImgAggBuckets.get(0).getKeyAsString();
                brandVo.setBrandImg(brand_img);
            }
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        //当前商品涉及到的所有属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        //获取子聚合里attr_id
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //获取属性id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());

            ///获取子聚合去获取名字和属性值
            List<? extends Terms.Bucket> attrNameAgg = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets();
            if (!CollectionUtils.isEmpty(attrNameAgg)) {
                String attr_name = attrNameAgg.get(0).getKeyAsString();
                //获取属性名字
                attrVo.setAttrName(attr_name);
            }
            //获取属性所有值
            List<? extends Terms.Bucket> attrValueAgg = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets();
            if (!CollectionUtils.isEmpty(attrValueAgg)) {
                List<String> attrValues = attrValueAgg.stream().map(item -> {
                    return item.getKeyAsString();
                }).collect(Collectors.toList());
                attrVo.setAttrValue(attrValues);
            }
            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);


        //页码
        result.setPageNum(param.getPageNum());

        //获取总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        //总页码
        long totalPage = total % EsConstant.PRODUCT_PAGESIZE == 0 ? total / EsConstant.PRODUCT_PAGESIZE : (total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPage);

        //导航页
        List<Integer> pageNav = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNav.add(i);
        }
        result.setPageNavs(pageNav);

        //构建面包屑导航数据
        List<SearchResult.NavVo> navVos = new ArrayList<>();
        List<String> attrs = param.getAttrs();
        if (!CollectionUtils.isEmpty(attrs)) {
            navVos = attrs.stream().map(item -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] split = item.split("_");
                navVo.setNavValue(split[1]);
                try {
                    R attrInfo = productFeignService.getAttrInfo(Long.parseLong(split[0]));
                    //收集一下筛选的id
                    result.getAttrIds().add(Long.parseLong(split[0]));
                    if (attrInfo.isSuccess()) {
                        String attr = JSON.toJSONString(attrInfo.get("attr"));
                        AttrResponseVo attrResponseVo = JSON.parseObject(attr, new TypeReference<AttrResponseVo>() {
                        });
                        navVo.setNavName(attrResponseVo.getAttrName());
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                }

                //取消面包屑要跳转的地方，将请求地址的url当前条件置空
                //拿到所有条件，去掉当前
                String replace = null;
                try {
                    replace = replaceQueryString(param, item, "attrs");
                    navVo.setLink("http://search.zky.com/list.html?" + replace);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return navVo;
            }).collect(Collectors.toList());
        }
        result.setNavs(navVos);


        //品牌，分类面包屑导航
        if (!CollectionUtils.isEmpty(param.getBrandId())) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            try {
                R r = productFeignService.brandInfos(param.getBrandId());
                if (r.isSuccess()) {
                    String attr = JSON.toJSONString(r.get("data"));
                    List<BrandResponseVo> responseVos = JSON.parseObject(attr, new TypeReference<List<BrandResponseVo>>() {
                    });
                    StringBuffer buffer = new StringBuffer();
                    String replace = "";
                    for (BrandResponseVo responseVo : responseVos) {
                        buffer.append(responseVo.getName() + ";");
                        replace = replaceQueryString(param, String.valueOf(responseVo.getBrandId()), "brandId");
                    }
                    navVo.setNavValue(buffer.toString());
                    navVo.setLink("http://search.zky.com/list.html?" + replace);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            navs.add(navVo);
        }


        //分类  不需要导航取消，暂时不做

        log.info("result:" + JSON.toJSONString(result));

        return result;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        String replace = "";
        try {
            String valueEn = URLEncoder.encode(value, "UTF-8");
            String replaceStr = valueEn.replace("+", "%20");
            replace = param.getQueryString().replace("&" + key + "=" + replaceStr, "");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return replace;
    }

    /**
     * 构建检索请求
     *
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        //构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (!StringUtils.isEmpty(param.getKeyword())) {
            //must 模糊匹配
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        //按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //按照品牌id查询
        if (!CollectionUtils.isEmpty(param.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        //按照指定的属性查询
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder query = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];//检索属性id
                String[] attrValues = s[1].split(":");//检索所有属性值
                query.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                query.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个都需要生成nestedQuery
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", query, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //按照库存查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        //按照价格区间查询
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] split = param.getSkuPrice().split("_");
            if (split.length == 2) {
                rangeQuery.gte(split[0]).lte(split[1]);
            } else if (split.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(split[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(split[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        sourceBuilder.query(boolQuery);

        //排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] split = param.getSort().split("_");
            SortOrder sortOrder = split[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(split[0], sortOrder);
        }

        //分页
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder().field("skuTitle").preTags("<b style='color:red'>")
                    .postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        //聚合数据查询
        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);

        //品牌聚合子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

        sourceBuilder.aggregation(brand_agg);

        //分类聚合
        TermsAggregationBuilder cataLog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        //分类子聚合
        cataLog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

        sourceBuilder.aggregation(cataLog_agg);


        //属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析当前attrId对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析当前attrId所有可能值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        nested.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(nested);

        System.out.println("构建成功DSL语句：" + sourceBuilder.toString());

        SearchRequest request = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return request;
    }
}
